package inseniarlingua

import java.awt.Color;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

class InseniarLinguaController {
    InseniarLinguaModel model
    InseniarLinguaView view

     void mvcGroupInit(Map args) {
		 model.user = model.words.keySet().iterator().next()
		 model.week = model.words[model.user].keySet().iterator().next()
     }

    // void mvcGroupDestroy() {
    //    // this method is called when the group is destroyed
    // }

    /*
        Remember that actions will be called outside of the UI thread
        by default. You can change this setting of course.
        Please read chapter 9 of the Griffon Guide to know more.
       
    def action = { evt = null ->
    }
    */
	def restartAction = { evt = null ->
		for (i in 0..<model.wordsByUserAndWeek.size()) {
			JTextField tf = model.textFields[i]
			tf.text = ""
		}
	}
	
	def changeUser = { evt = null ->
		println "Into changeUser"
		def items = model.words[model.userCB.selectedItem].keySet()
		def cbm = new DefaultComboBoxModel(new Vector(items))
		model.weekCB.model = cbm
		model.week = items[0]
		model.weekCB.selectedItem = model.week 
	}
	
	def changeWeek = { evt = null ->
		println "Into changeWeek"
		//model.user = model.userCB.selectedItem
		model.week = model.weekCB.selectedItem
		view.populateTransPanel()
//		def items = model.words[user][week]
//		def cbm = new DefaultComboBoxModel(new Vector(items))
//		model.weekCB.model = cbm
	}
	
	def finishAction = { evt ->
		println "Into finishAction"
		int nwrong = 0
		int i = 0
		model.wordsByUserAndWeek.each { k,exp ->
			JTextField tf = model.textFields[i] 
			def act = tf.text.trim()
			def flag = exp.equalsIgnoreCase(act)
			println "$k=$exp.  $act  $flag"
			Color color
			if (flag) {
				color = Color.BLACK
			}
			else {
				nwrong++
				color = Color.RED
			}
			tf.foreground = color
			i++
		}
		def msg = (nwrong <= 0) ? "Congratulation!!!  All are correct." 
			: "Sorry mate.  You have $nwrong of out ${i} wrong.\nPlease take the test again." 
		JOptionPane.showMessageDialog(null, msg)
    }
}
